<?php
namespace app\client\behavior;

use think\Request;
use think\Session;
use think\Db;
use think\Url;
use think\Controller;

class Config extends Controller
{
    public function run(&$params)
    {

        $CONTROLLER_NAME = Request::instance()->controller();

        if ($CONTROLLER_NAME == 'Dashboard' || $CONTROLLER_NAME == 'Statistics') {

            // 读取用户配置
            if (empty(cache('province'))) {
                $province = Db::name('area')->where(['area_deep' => ['in', '1,2']])->select();
                cache('province', recursion_node($province, 0, 'city', 'area_parent_id', 'area_id'));

            }

            if (empty(cache('stat_goods_' . Session::get('shop_id')))) {

                // 上架商品
                Db::name('shop_goods')->where(['state' => '1', 'member_id' => Session::get('shop_id')])
                    ->cache('stat_goods_' . Session::get('shop_id'), 300)->count();

                // 成交订单总数
                Db::name('member_order')->where(['status' => ['in', '1,2,3,4'], 'shop_id' => Session::get('shop_id')])
                    ->cache('stat_order_' . Session::get('shop_id'), 300)->count();

                // 成交订单总金额
                Db::name('member_order')->where(['status' => ['in', '1,2,3,4'], 'shop_id' => Session::get('shop_id')])
                    ->cache('stat_order_price_' . Session::get('shop_id'), 300)->sum('price');

                // 商品总销量
                Db::name('shop_goods')->where(['state' => '1', 'member_id' => Session::get('shop_id')])
                    ->cache('stat_sales_volume_' . Session::get('shop_id'), 300)->sum('sale_number');

                // 退款订单总数
                Db::name('member_order')->where(['status' => 10, 'shop_id' => Session::get('shop_id')])
                    ->cache('stat_retreat_order_' . Session::get('shop_id'), 300)->count();

                // 退款订单总金额
                Db::name('member_order')->where(['status' => 10, 'shop_id' => Session::get('shop_id')])
                    ->cache('stat_retreat_order_price_' . Session::get('shop_id'), 300)->sum('price');


            }

            // 店铺累计访问人次
            Db::name('shop_hit')->where('shop_id', Session::get('shop_id'))->cache('shop_flow_total_' . Session::get('shop_id'), 300)->value('hits');

            // 今日访问量
            Db::name('shop_hit')->where(['shop_id' => Session::get('shop_id'), 'hit_time' => date('Y-m-d')])->cache('shop_today_flow' . Session::get('shop_id'), 300)->value('hits');

        }

        if ($CONTROLLER_NAME <> 'Login') {
            if (false == Session::has('shop_id')) {
                $this->redirect(Url::build('client/login/index'));
            }
        }

    }
}